package com.sodaopen.study.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.sodaopen.study.entity.Chapter;

import java.util.List;
import java.util.Map;

public interface ChapterMapper {

	@Select("select * from t_chapter where course_id=${id} order by pid, sort ")
	List<Chapter> selectByCourseId(Integer id);

	@Select("select c.*, ifnull((select 'Y' from t_chapter_finish f where f.user_id=#{userId} and chapter_id=c.id),'N') finished " +
			"from t_chapter c where course_id=#{courseId} order by pid, sort")
	List<Chapter> selectByCourseIdFinish(@Param("courseId")Integer courseId, @Param("userId")Integer userId);

	@Select("select * from t_chapter where id=${id}")
	Chapter selectById(Integer id);

	@Select("select c.*, ifnull((select 'Y' from t_chapter_finish f where f.user_id=#{userId} and chapter_id=c.id),'N') finished from t_chapter c where id=${id}")
	Chapter selectByIdFinish(@Param("id")Integer id, @Param("userId")Integer userId);

	@Insert("insert into t_chapter_finish(user_id, chapter_id) values(#{userId}, #{chapterId})")
    void insertFinishRecord(@Param("userId")Integer userId, @Param("chapterId")Integer chapterId);

	@Select("select * from t_locked where user_id=#{userId} and course_id=#{courseId}")
	Map selectLockedByPrimaryKey(@Param("userId")Integer userId, @Param("courseId")Integer courseId);

	@Select("select count(*) from t_chapter c where c.pid=#{pid} " +
			"and not exists(select null from t_chapter_finish f where f.user_id=#{userId} and f.chapter_id = c.id)")
	Integer selectUnfinishCount(@Param("userId")Integer userId, @Param("pid")Integer pid);

	@Select("select count(*) from t_chapter c where c.course_id=#{courseId} and pid is null " +
			"and not exists(select null from t_chapter_finish f where f.user_id=#{userId} and f.chapter_id = c.id)")
	Integer selectUnfinishCourse(@Param("userId")Integer userId, @Param("courseId")Integer courseId);

	@Insert("insert into t_locked(user_id, course_id, chapter_id) values(#{userId}, #{courseId}, #{chapterId})")
	void insertLockedRecord(@Param("userId")Integer userId, @Param("courseId")Integer courseId, @Param("chapterId")Integer chapterId);

    Integer selectMaxSort(@Param("pid") Integer pid, @Param("courseId") Integer courseId);

    @Insert("insert into t_chapter(name, content, title, icon, sort, pid, course_id, media_id, locked) " +
			"values(#{name}, #{content}, #{title}, #{icon}, #{sort}, #{pid}, #{courseId}, #{mediaId}, #{locked})")
	void insertChapter(Chapter chapter);
}
